<<<<<<< HEAD
import router, {
  asyncRoutes
} from '@/router'
import {
  $api
} from '@/api'
import {
  SET_ROUTES
} from '../types'
=======
import { asyncRoutes } from '@/router'
import { SET_ROUTES } from '../types'
>>>>>>> 85d0debcca44c4a451c9e968272089f1bfdcaf45

const state = {
  routes: []
}

/**
 * 判断用户是否有权限
 * @param routerAuthKey
 * @param route
 */
function hasPermission(routerAuthKey, route) {
  if (route.meta && route.meta.authMenuKey) {
    return routerAuthKey.some(item => route.meta.authMenuKey === item.menuKey || route.meta.authMenuKey.includes(item.menuKey))
  } else {
    return true
  }
}

/**
 * 递归路由表
 */
export function filterAsyncRoutes(routes, routerAuthKey) {
  const res = []

  routes.forEach(route => {
    let tmp = {
      ...route
    }
    if (hasPermission(routerAuthKey, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, routerAuthKey)
      }
      res.push(tmp)
    }
  })

  return res
}

const mutations = {
  SET_ROUTES(state, routes) {
    state.routes = routes
  }
}

const actions = {
  generateRoutes({
    commit
  }) {
    return new Promise(async resolve => {
      try {
        const {
          data
        } = await $api('user/fechGetUserMenu');
        const routers = filterAsyncRoutes(asyncRoutes, data.map(item => item.menuKey));
        commit(SET_ROUTES, routers)
        router.addRoutes(routers)
      } catch (err) {
        console.error(err)
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
